import {
  Toast
} from "vant";
import EXIF from 'exif-js'
import Vue from "vue";
import Router from "../router";
import qs from "qs";

class NativeUtil {
  static singleInstance;
  static themeColor='#3676F5';
  static instance() {
    if (!this.singleInstance) {
      this.singleInstance = new NativeUtil();
    }
    return this.singleInstance;
  }

  // getPhoto(type, successBack, deviceName, quality, clearWaterMark, moduleName, imageCompressType) {
  getPhoto(type, successBack, paramsObject) {
    if (this.isDeviceReady() != true) {
      Toast.fail("努力加载中");
      return;
    }
    var deviceName;
    var quality;
    var clearWaterMark;
    var moduleName;
    var imageCompressType;

    if(paramsObject) {
      deviceName = paramsObject.deviceName ? paramsObject.deviceName : "";
      quality = paramsObject.quality ? paramsObject.quality : 50;
      clearWaterMark = paramsObject.clearWaterMark ? paramsObject.clearWaterMark : false;
      moduleName = paramsObject.moduleName ? paramsObject.moduleName : "";
      imageCompressType = paramsObject.imageCompressType ? paramsObject.imageCompressType : 1;
    }
    console.log("拍照, 设备名称：" + deviceName);
    console.log("拍照, 图片质量：" + quality);
    console.log("拍照, 是否水印：" + clearWaterMark);
    console.log("拍照, 模块名称：" + moduleName);
    console.log("拍照, 压缩类型：" + imageCompressType);
    console.log("-----------------------------------：");

    // let unableWorker = false;
    // let w;
    // if (
    //   typeof Worker === "undefined" ||
    //   window["OffscreenCanvas"] == undefined
    // ) {
    //   unableWorker = true;
    //   console.log("浏览器不支持Web Worker");
    // }
    // document.getElementById("ajaxLoadingWrapper").classList.remove("hide");
    console.log('----------------------调用照片插件');
    navigator.camera.getPicture(
      imgSrc => {
        console.log('----------------------照片插件回调-------------------------------');
        
        if (clearWaterMark) {
          successBack && successBack(imgSrc);
          return;
        }

        console.log("开始加载转圈圈，加载水印");
        var toast = Toast.loading({
          duration: 0,
          message: "正在加载水印中...",
          forbidClick: true
        });
        console.log("加载水印");
     
        let imgSize = this.getImgSize(imgSrc);

        //创建 Web Worker 对象
        // if (!unableWorker) {
        //   w = new Worker("./photoWorker.js");
        //   w.onmessage = function (event) {
        //     // document.getElementById("ajaxLoadingWrapper").classList.add("hide");
        //     console.log(event.data);
        //     successBack && successBack(event.data);
        //   };
        //   w.postMessage({
        //     deviceName: deviceName,
        //     src: imgSrc,
        //     isDlydt: process.env.VUE_APP_SYSTEM_ENVIRONMENT == "dlydt"
        //   });
        // } else {

        // let time = new Date().toLocaleString();
        let time = Vue.prototype.$formatDate(new Date(), 'yyyy-MM-dd HH:mm');
        if(moduleName == "yglz") {
          //一杆六照
          var userInfo = JSON.parse(Vue.prototype.$dealMsg("SDXJ_USER_INFO"));
          var userName = userInfo.userName;
          time = userName + "   " + time;
        }
        var cvs = document.createElement("canvas");
        document.body.appendChild(cvs);
        var ctx = cvs.getContext("2d");
        var img = new Image();
        let base64Url;
        var fontSize = 30;
        img.onload = function () {
          console.log('onload')
          // 将图片画到canvas上面上去！
          if (moduleName == "SignIn") {
            cvs.width = 350;
            cvs.height = 350;
            ctx.drawImage(img, 0, 0, 350, 350);
            // ctx.font = "18px 微软雅黑";
            // fontSize = 18; 

            // ctx.textBaseline = "bottom";
            // ctx.fillStyle="gray";
            // var rectWidth = ctx.measureText(time).width;
            // ctx.fillRect(50, 50-fontSize-2, rectWidth, fontSize);

            // ctx.fillStyle = "rgba(252,255,255,0.5)";
            // ctx.fillText(`${time}`, 50, 50); //选择位置

          } else {
            let width
            let height
            // if(imgSize<150||imgSize==150){
              console.log('比例1')
              width= img.width * 1;
              height= img.height * 1;
            // }else if(imgSize>150&&imgSize<500){
            //   console.log('0.6')
            //   width= img.width * 1;
            //   height= img.height * 1;
            // }else if(imgSize>500||imgSize==500){
            //   console.log('0.4')
            //   width= img.width * 1;
            //   height= img.height * 1;
            // }
            // var rate = width / height
            cvs.width = width;
            cvs.height = height;
            ctx.drawImage(img, 0, 0, width, height);
            console.log("宽度：" + width);
            // if(width <= 1000) {
            //   fontSize = 40;
            // }else if(width <= 2000){
            //   fontSize = 80;
            // }else if(width <= 3000){
            //   fontSize = 110;
            // }else if(width <= 4000){
            //   fontSize = 150;
            // }
            // ctx.font = fontSize + "px 微软雅黑";

            // ctx.textBaseline = "bottom";
            // ctx.fillStyle="gray";
            // var rectWidth = ctx.measureText(time).width;
            // ctx.fillRect(200, 200-fontSize-4, rectWidth, fontSize);

            // ctx.fillStyle = "rgba(252,255,255,0.5)";
            // ctx.fillText(`${time}`, 200, 200); //选择位置

          }
          if(time != null) {
            fontSize = cvs.width/27 ;
            console.log("文字大小" + fontSize);
            ctx.font = fontSize + "px 微软雅黑";

            var startPositionX = cvs.width/20;
            // var startPositionY = cvs.height/20;
            var startPositionY = startPositionX;
            ctx.fillStyle="gray";
            var rectWidth  = ctx.measureText(time).width;
            //fillRect(坐标，坐标，长度，宽度)
            ctx.fillRect(startPositionX, cvs.height - fontSize - startPositionY, rectWidth, fontSize);
  
            ctx.textBaseline = 'top';
            ctx.fillStyle = "rgba(252,255,255,0.5)";
            //fillText(文字，坐标，坐标)
            ctx.fillText(`${time}`,  startPositionX, cvs.height- fontSize - startPositionY);

          }



          // if(deviceName != null){
          //   ctx.fillStyle="gray";
          //   var rectWidth  = ctx.measureText(deviceName).width;
          //   console.log("设备名称宽度：" + rectWidth);
          //   console.log("图片宽度：" + cvs.width);
          //   //fillRect(坐标，坐标，长度，宽度)
          //   ctx.fillRect(cvs.width-rectWidth - 100, cvs.height-100-fontSize-4, rectWidth, fontSize);
  
          //   ctx.textAlign = "right";
          //   ctx.textBaseline = "bottom";
          //   ctx.fillStyle = "rgba(252,255,255,0.5)";
          //   ctx.fillText(`${deviceName}`, cvs.width-100, cvs.height-100);
          // }

          if(deviceName != null){
            var startPositionX = cvs.width/20;
            // var startPositionY = cvs.height/20;
            var startPositionY = startPositionX;
            ctx.fillStyle="gray";
            var rectWidth  = ctx.measureText(deviceName).width;
            console.log("设备名称宽度：" + rectWidth);
            console.log("图片宽度：" + cvs.width);
            console.log("图片高度：" + cvs.height);
            //fillRect(x坐标，y坐标，长度，宽度)
            ctx.fillRect(cvs.width-rectWidth - startPositionX, cvs.height - fontSize - startPositionY, rectWidth, fontSize);
  
            ctx.textBaseline = 'top';
            ctx.fillStyle = "rgba(252,255,255,0.5)";
            //fillText(文字，x坐标，y坐标)
            ctx.fillText(`${deviceName}`, cvs.width-rectWidth - startPositionX, cvs.height- fontSize - startPositionY);
          }

          
          base64Url = cvs.toDataURL("image/jpeg");
          var compressSize = base64Url? (base64Url.length * 0.75).toFixed(2) : 0;
          console.log("图片大小为：" + compressSize / 1024/1024 + " M");
            // 大小超过2M 降低质量
          if(compressSize > 5 * 1024 * 1024){
            console.log("大于5M, 大小为：" + compressSize / 1024/1024 + " M");
            console.log("压缩图片");
            base64Url = cvs.toDataURL("image/jpeg", 0.1);
            compressSize = base64Url? (base64Url.length * 0.75).toFixed(2) : 0;
            console.log("压缩完图片大小为：" + compressSize / 1024/1024 + " M");

          }else if(compressSize > 4 * 1024 * 1024){
            console.log("大于4M, 大小为：" + compressSize / 1024/1024 + " M");
            console.log("压缩图片");
            base64Url = cvs.toDataURL("image/jpeg", 0.20);
            compressSize = base64Url? (base64Url.length * 0.75).toFixed(2) : 0;
            console.log("压缩完图片大小为：" + compressSize / 1024/1024 + " M");
          }else if(compressSize > 3 * 1024 * 1024){
            console.log("大于3M, 大小为：" + compressSize / 1024/1024 + " M");
            console.log("压缩图片");
            base64Url = cvs.toDataURL("image/jpeg", 0.25);
            compressSize = base64Url? (base64Url.length * 0.75).toFixed(2) : 0;
            console.log("压缩完图片大小为：" + compressSize / 1024/1024 + " M");
          }else if(compressSize > 2 * 1024 * 1024){
            console.log("大于2M, 大小为：" + compressSize / 1024/1024 + " M");
            console.log("压缩图片");
            base64Url = cvs.toDataURL("image/jpeg", 0.5);
            compressSize = base64Url? (base64Url.length * 0.75).toFixed(2) : 0;
            console.log("压缩完图片大小为：" + compressSize / 1024/1024 + " M");
          }
          console.log("加载水印结束-------------------------------------");
          Toast.clear();
          base64Url = base64Url.replace("data:image/jpeg;base64,", "");
          document.body.removeChild(cvs);

          // document.getElementById("ajaxLoadingWrapper").classList.add("hide");
          successBack && successBack(base64Url);
        };
        img.src = "data:image/png;base64," + imgSrc;
        // }
      },
      error => {
        // document.getElementById("ajaxLoadingWrapper").classList.add("hide");
      }, {
        quality: quality,
        sourceType: type == "camera" ? 1 : 2, /// 0：照片库，1：相机
        destinationType: 0, ///  0: 返回base64编码字符串,1: 返回图片文件URI, 2: 返回图片本机URI。默认base64
        targetWidth: 720,
        targetHeight: 1280,
        imageCompressType:imageCompressType,
      }
    );
  }
   getImgSize(data) {
    //data为base64图片

    var size = 0;

    if (data) {
      // 获取base64图片byte大小

      const equalIndex = data.indexOf("="); // 获取=号下标

      if (equalIndex > 0) {
        const str = data.substring(0, equalIndex); // 去除=号

        const strLength = str.length;

        const fileLength = strLength - (strLength / 8) * 2; // 真实的图片byte大小

        size = Math.floor(fileLength); // 向下取整
      } else {
        const strLength = data.length;

        const fileLength = strLength - (strLength / 8) * 2;

        size = Math.floor(fileLength); // 向下取整
      }
    } else {
      size = null;
    }

    return size/1024; //得到的是字节大小
  }
  getMR25MR21(successBack, failBack) {
    if (this.isDeviceReady() != true) {
      failBack && failBack();
      return;
    }

    navigator.rfid.queryMR2125(
      function (value) {
        successBack && successBack(value);
      },
      function (msg) {
        failBack && failBack();
        Toast.fail(msg);
      }
    );
  }

  getMR26(successBack, failBack) {
    if (this.isDeviceReady() != true) {
      failBack && failBack();
      return;
    }

    navigator.rfid.queryMR26(
      function (value) {
        successBack && successBack(value);
      },
      function (msg) {
        Toast.fail(msg);
      }
    );
  }

  getPosition(successBack, failBack,isGetCache) {
    var userPositionInfo = Vue.prototype.$dealMsgLS('GMMS_USER_POSITION_INFO');
    // console.log("用户位置存储信息：" + userPositionInfo);
    if(userPositionInfo&&isGetCache) {
      // console.log("进入用户信息：" );
      userPositionInfo = JSON.parse(userPositionInfo);
      var userPositionTime = userPositionInfo.time;
      var nowDate = new Date().getTime();
      var userPositionDate = new Date(userPositionTime).getTime();
      //间隔2分钟
      var BETWEEN_SECONDS = 120;
      var compareSeconds = parseInt(nowDate - userPositionDate) / 1000;
      // console.log("比较秒数：" + compareSeconds);
      if(compareSeconds > 0 && compareSeconds <=　BETWEEN_SECONDS) {
        var position = {};
        position["coords"] = {};
        position["coords"]["latitude"] = userPositionInfo.lat;
        position["coords"]["longitude"] = userPositionInfo.lng;
        console.log("缓存回调，位置信息 " , position);
        successBack(position);
        return;
      }
    }

    if (this.isDeviceReady() != true) {
      // console.log('判断设备未准备就绪');
      // console.log("~~~~~~~~~~~~~~~~~~~~~插件未初始化，回调报错函数" );
      failBack && failBack();
      return;
    }
    // console.log("~~~~~~~~~~~~~~~~~~~~~开始真正调用定位插件" );
    // console.log('调用gps定位插件');
    navigator.gps.getSGLocation(
      (position) => {
        // console.log("~~~~~~~~~~~~~~~~~~~~~真正调用定位插件回调成功" );
        // console.log('调用gps插件成功，定位信息：' + JSON.stringify(position));
        // console.log("-------------getPosition-------------准备存储用户位置信息");
        var positionInfo = {};
        var nowDate = new Date();
        var time = Vue.prototype.$formatDate(nowDate, "yyyy-MM-dd HH:mm:ss");
        // console.log("getPosition    存储位置信息：" + time);
        positionInfo.time = time;
        positionInfo.lng = position["longitude"];
        positionInfo.lat = position["latitude"];
        Vue.prototype.$dealMsgLS('GMMS_USER_POSITION_INFO', JSON.stringify(positionInfo));
        // console.log("--------------getPosition------------存储用户位置信息", positionInfo);

        position["coords"] = {};
        position["coords"]["latitude"] = position["latitude"];
        position["coords"]["longitude"] = position["longitude"];
        // console.log('coords.lat='+position["coords"]["latitude"])
        // console.log('coords.lon='+position["coords"]["longitude"])
        successBack && successBack(position);
      },
      (error) => {
        console.log('获取定位失败,' + JSON.stringify(error));
        Toast.fail("获取定位失败啦");
        failBack && failBack(error);
      },
      "gps"
    );
  }

  getLocation(successBack, failBack) {
    //获取上一次位置信息
    //取全局变量
    //取存储变量
    //实时获取位置信息
    if (this.isDeviceReady() != true) {
      console.log('判断设备未准备就绪');
      failBack && failBack();
      return;
    }
    // console.log("~~~~~~~~~~~~~~~~~~~~~开始真正调用定位插件" );
    // console.log('调用gps定位插件');
    navigator.gps.getLocation(
      (position) => {
        // console.log("~~~~~~~~~~~~~~~~~~~~~真正调用定位插件回调成功" );
        // console.log('调用gps插件成功，定位信息：' + JSON.stringify(position));
        // console.log("-----------getLocation---------------准备存储用户位置信息");
        var positionInfo = {};
        var nowDate = new Date();
        var time = Vue.prototype.$formatDate(nowDate, "yyyy-MM-dd HH:mm:ss");
        // console.log("getLocation   存储时间：" + time);
        positionInfo.time = time;
        positionInfo.lng = position["longitude"];
        positionInfo.lat = position["latitude"];
        Vue.prototype.$dealMsgLS('GMMS_USER_POSITION_INFO', JSON.stringify(positionInfo));
        // console.log("-------------getLocation-------------存储用户位置信息", positionInfo);

        position["coords"] = {};
        position["coords"]["latitude"] = position["latitude"];
        position["coords"]["longitude"] = position["longitude"];
        // console.log('coords.lat='+position["coords"]["latitude"])
        // console.log('coords.lon='+position["coords"]["longitude"])
        successBack && successBack(position);
      },
      (error) => {
        console.log('获取定位失败,' + JSON.stringify(error));
        Toast.fail("获取定位失败啦");
        failBack && failBack(error);
      },
      "gps"
    );
  }

  closeRFID() {
    navigator.rfid && navigator.rfid.queryClose && navigator.rfid.queryClose();
  }

  isDeviceReady() {
    if (deviceReady == true) {
      return true;
    } else {
      Toast.loading({
        message:"加载中",
        forbidClick:true,
        loadingType:"spinner"
      });
      return false;
    }
  }

  // 处理控件显示的时间格式
  formatterDateTime(type, value) {
    // 格式化选择器日期
    if (type === "year") {
      return `${value}年`;
    } else if (type === "month") {
      return `${value}月`;
    } else if (type === "day") {
      return `${value}日`;
    } else if (type === "hour") {
      return `${value}时`;
    } else if (type === "minute") {
      return `${value}分`;
    } 
    return value;
  }
  formatDate(date,type) {
    if(!date){
      date = new Date();
    }
    if(!type){
      type='/'
    }
   let y = date.getFullYear();
   let MM = date.getMonth() + 1;
   MM = MM < 10 ? "0" + MM : MM;
   let d = date.getDate();
   d = d < 10 ? "0" + d : d;
   let h = date.getHours();
   h = h < 10 ? "0" + h : h;
   let m = date.getMinutes();
   m = m < 10 ? "0" + m : m;
   let s = date.getSeconds();
   s = s < 10 ? "0" + s : s;
   return y + type + MM + type + d + " " + h + ":" + m + ":" + s;
  }
  formatTime(date,type='/') {
   if(!date){
     date = new Date();
   }
   let y = date.getFullYear();
   let MM = date.getMonth() + 1;
   MM = MM < 10 ? "0" + MM : MM;
   let d = date.getDate();
   d = d < 10 ? "0" + d : d;
   let h = date.getHours();
   h = h < 10 ? "0" + h : h;
   let m = date.getMinutes();
   m = m < 10 ? "0" + m : m;
   let s = date.getSeconds();
   s = s < 10 ? "0" + s : s;
   return y + type + MM + type + d + " " + h + ":" + m;
  }
  getImgLocation(file){
    let _this = this
    return new Promise((resolve,reject)=>{
      EXIF.getData(file,function(){
        //图片包含的所有信息(例：拍照方向、相机设备型号、拍摄时间、ISO 感光度、GPS 地理位置等数据。)
        const imgAllInfo = EXIF.getAllTags(this);
        const imgLon = EXIF.getTag(this, 'GPSLongitude')
        const imgLat = EXIF.getTag(this, 'GPSLatitude')
        let res={
          originalTime:EXIF.getTag(this, 'DateTimeOriginal')
        };
        if(res.originalTime&&typeof res.originalTime=='string'){
          var list=res.originalTime.split(" ")
          if(list.length==2&&list[0].includes(':')){
            list[0]=list[0].replace(':','-').replace(':','-')
            res.originalTime=list[0]+' '+list[1]
          }
        }
        if(imgLon && imgLat){
          //计算出经纬度并保留6为小数
          res.lon = (imgLon[0] + imgLon[1]/60 + imgLon[2]/60/60).toFixed(6)
          res.lat = (imgLat[0] + imgLat[1]/60 + imgLat[2]/60/60).toFixed(6) 
        }
        resolve(res) 
      })
    })
   
  }
  //根据字符串创建日期对象
 _createDate (dateStr) {
    if (!dateStr) {
        return null;
    }
    var ps = dateStr.split(" ");
    var pd = ps[0].split("-");
    var pt = ps.length > 1 ? ps[1].split(":") : [0, 0, 0];
    return new Date(pd[0], pd[1] - 1, pd[2], pt[0], pt[1], pt[2]);
  }
  // 扫码识别
  scanQrCode(successBack, failBack) {
    if (this.isDeviceReady() != true) {
      failBack && failBack();
      return;
    }
    navigator.forward.goToScanTwoDiemCode(successBack, failBack);
  }
}
class Utils{ 
  static sms = '86C631'+'80C280'+'6ED1F4'+'7B859D'+'E501215B'; 
  static dateFtt (date,fmt) {
    if (!date) {
        date = new Date();
    }
    const o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        S: date.getMilliseconds(), //毫秒
    };

    let fmtN = fmt ? fmt : 'yyyy-MM-dd';
    if (/(y+)/.test(fmtN)) {
        fmtN = fmtN.replace(RegExp.$1, (`${date.getFullYear()}`).substr(4 - RegExp.$1.length));
    }
    Object.keys(o).forEach((k) => {
        if (new RegExp(`(${k})`).test(fmtN)) {
            fmtN = fmtN.replace(RegExp.$1, (RegExp.$1.length === 1) ? (`${o[k]}`) : (`00${o[k]}`.substr(`${o[k]}`.length)));
        }
    });
    return fmtN;
  }
  static moveDiv(dom){
    var odiv=document.querySelector(dom) 
    odiv.ontouchstart = (e) => {
      //算出鼠标相对元素的位置
      if(e.touches&&e.touches[0]){  
      let disX = e.touches[0].clientX - odiv.offsetLeft;
      let disY = e.touches[0].clientY - odiv.offsetTop; 
      document.ontouchmove = (e)=>{
          //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
          if(e.touches&&e.touches[0]){ 
            let left = e.touches[0].clientX - disX;    
            let top = e.touches[0].clientY - disY; 
    
            //移动当前元素
            odiv.style.left = left + 'px';
            odiv.style.top = top + 'px'; 
          }
      };
      document.ontouchend = (e) => {
          document.ontouchmove = null;
          document.ontouchend = null; 
      };
      }
    };
     
  }
  static goProjectPath(data,path=''){
    if(process.env.NODE_ENV === "production"){
      const str=qs.stringify(data.query) 
      window.location.href=`${path}/index.html#/${data.name}?${str}`
      return
    }
    Router.push(data)
  }
}
export {
  NativeUtil,Utils
};
